import {
  getConnect
} from '@/utils/auth'
import genrateSignature from '@/common/wechatjssdk/sign'
import WechatJSSDK from 'wechat-jssdk/dist/client.umd'

/**
 * 微信JSSDKBridge
 *
 * @export
 * @class JSBridge
 */
export default class JSBridge {
  constructor () {
    this.name = 'JSBridge'
    this.instance = null
    // 默认设置
    this.debug = false
    this.jsApiList = ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo', 'onMenuShareQZone', 'chooseWXPay']
    // 自定义微信js链接
    this.customUrl = 'http://res.wx.qq.com/open/js/jweixin-1.6.0.js'
  }

  static getInstance () {
    if (!this.instance) {
      this.instance = new JSBridge()
    }
    return this.instance
  }

  /**
   * JSBridge初始化
   *
   * @param {*} callback
   * @returns
   * @memberof JSBridge
   */
  _init (config) {
    console.group('Wechat JSSDK')

    let signData = this.getSignData()
    console.log('[SignData]', signData)

    const wechatConfig = Object.assign({
      debug: this.debug,
      jsApiList: this.jsApiList,
      customUrl: this.customUrl
    }, signData, config)
    console.log('[wechatConfig]', wechatConfig)

    const wechatObj = new WechatJSSDK(wechatConfig)

    if (Object.prototype.hasOwnProperty.call(wechatObj, 'wx')) {
      console.log(wechatObj)
      const wx = wechatObj.wx
      wx.ready(() => {
        console.log('ready')
      })
      wx.error((res) => {
        console.log('error')
        console.log(res)
      })
      wechatObj.initialize().then(obj => {
        // set up your share info, "w" is the same instance as "wechatObj"
        console.log(obj)
      }).catch(err => {
        console.error(err)
      })
    }

    return wechatObj.initialize()
  }

  /**
   * 获取签名配置信息
   *
   * @param {*} url
   * @memberof JSBridge
   */
  getSignData () {
    const data = getConnect()
    console.log('[getConnect DATA]', data)

    if (data && data.sdk) {
      let signData = genrateSignature(data.sdk.jsapi_ticket, location.href)
      return Object.assign({}, signData, {
        appId: data.sdk.appId
      })
    } else {
      return null
    }
  }

  /**
   * 分享
   *
   * @param {*} data
   * @memberof JSBridge
   */
  updateAppMessageShareData (data) {
    console.log('[share data]', data)
    return new Promise((resolve, reject) => {
      if (!data) {
        console.log('[reject data]', data)
        reject(data)
      }

      if (!data.link) {
        data.link = location.href
      }
      if (!data.imgUrl) {
        data.imgUrl = 'http://attach.youyuegw.com/assets/brand/app.png'
      }
      if (!data.title) {
        data.title = '优越定制'
      }
      if (!data.desc) {
        data.desc = '优越定制'
      }

      this._init().then(wx => {
        console.log('[wx]', wx)
        wx.wx.ready(() => {
          // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）
          wx.callWechatApi('updateAppMessageShareData', {
            title: data.title, // 分享标题
            desc: data.desc, // 分享描述
            link: data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: data.imgUrl, // 分享图标
            success: function () {
              resolve('[updateAppMessageShareData] successful')
            }
          })
          // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
          wx.callWechatApi('updateTimelineShareData', {
            title: data.title, // 分享标题
            link: data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: data.imgUrl, // 分享图标
            success: function () {
              resolve('[updateTimelineShareData] successful')
            }
          })
        })
      }).catch(err => {
        console.error('[err]', err)
        reject(err)
      })
      console.groupEnd('Wechat JSSDK')
    })
  }

  successed (name) {
    return name + 'success'
  }

  canceled (name) {
    return name + 'cancel'
  }
}
